/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.merak.core.text.json.jsonfiers;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.merak.core.text.json.DateStyle;
import org.merak.core.text.json.JsonContext;

public class DateFormatJsonfier extends Jsonfier {

	//~ Attributes ///////////////////////////////////////////////////////////////
	//****************************************************************************
	private DateFormat format;
	
	//~ Constructors /////////////////////////////////////////////////////////////
	//****************************************************************************
	public DateFormatJsonfier(String format) {
		this.format = new SimpleDateFormat(format);
	}
	//****************************************************************************
	public DateFormatJsonfier(DateStyle style) {
		this.format = DateFormat.getDateInstance(style.getId());
	}
	//****************************************************************************
	public DateFormatJsonfier(DateStyle dateStyle,DateStyle timeStyle) {

		if (!dateStyle.isUnknown() && !timeStyle.isUnknown()) {
			this.format = DateFormat.getDateTimeInstance(dateStyle.getId(),timeStyle.getId());
		}
		else if (!dateStyle.isUnknown()) {
			this.format = DateFormat.getDateInstance(dateStyle.getId());
		}
		else if (!timeStyle.isUnknown()) {
			this.format = DateFormat.getTimeInstance(timeStyle.getId());
		}		
		else {
			this.format = DateFormat.getInstance();
		}

	}		
	
	//~ Methods //////////////////////////////////////////////////////////////////
	//****************************************************************************
	@Override
	public void render(Object object,JsonContext context) throws Exception {

		if(object == null) {
			context.getBuffer().append("null");
		}
		else {	
			context.getBuffer()			
			.append('"')
			.append(format.format(object))
			.append('"');			
		}

	}
	//****************************************************************************

}
